"""知网检测平台实现"""

from typing import Optional, Dict, Any
from datetime import datetime

from app.models.enums import DetectionStatus, DetectionPlatform
from app.models.response import TextDetectionResponse
from app.utils.exceptions import PlatformAPIException
from .base import BaseDetectionPlatform


class ZhiwangDetectionPlatform(BaseDetectionPlatform):
    """知网检测平台"""
    
    def __init__(self, api_url: str, api_key: str):
        super().__init__(api_url, api_key, DetectionPlatform.ZHIWANG)
    
    async def submit_detection(self, text: str, title: Optional[str] = None, 
                             author: Optional[str] = None) -> TextDetectionResponse:
        """提交知网检测任务"""
        try:
            self.logger.info("提交知网检测任务")
            
            # 验证文本
            if not self._validate_text_for_platform(text):
                raise PlatformAPIException(
                    self.platform_name.value, 
                    "文本不符合知网检测要求"
                )
            
            # 准备请求数据
            data = {
                "text": text,
                "title": title or "未命名文档",
                "author": author or "匿名",
                "detection_type": "academic",  # 知网学术检测
                "language": "zh-cn"  # 中文检测
            }
            
            # 发送API请求
            response = await self._make_api_request("POST", "/detect", data)
            
            # 处理响应
            task_id = response.get("task_id")
            if not task_id:
                raise PlatformAPIException(
                    self.platform_name.value, 
                    "未获取到任务ID"
                )
            
            return self._create_response(
                task_id=task_id,
                status=DetectionStatus.PENDING
            )
            
        except PlatformAPIException:
            raise
        except Exception as e:
            self.logger.error(f"知网检测任务提交失败: {e}")
            raise PlatformAPIException(
                self.platform_name.value, 
                f"任务提交失败: {str(e)}"
            )
    
    async def get_detection_result(self, task_id: str) -> TextDetectionResponse:
        """获取知网检测结果"""
        try:
            self.logger.info(f"获取知网检测结果: {task_id}")
            
            # 发送查询请求
            response = await self._make_api_request("GET", f"/result/{task_id}")
            
            # 解析响应
            status_map = {
                "pending": DetectionStatus.PENDING,
                "processing": DetectionStatus.PROCESSING,
                "completed": DetectionStatus.COMPLETED,
                "failed": DetectionStatus.FAILED
            }
            
            status = status_map.get(
                response.get("status", "pending"), 
                DetectionStatus.PENDING
            )
            
            similarity_rate = response.get("similarity_rate")
            if similarity_rate is not None:
                similarity_rate = float(similarity_rate) / 100  # 转换为小数
            
            report_url = response.get("report_url")
            
            return self._create_response(
                task_id=task_id,
                status=status,
                similarity_rate=similarity_rate,
                report_url=report_url
            )
            
        except Exception as e:
            self.logger.error(f"获取知网检测结果失败: {e}")
            raise PlatformAPIException(
                self.platform_name.value, 
                f"获取结果失败: {str(e)}"
            )
    
    async def cancel_detection(self, task_id: str) -> bool:
        """取消知网检测任务"""
        try:
            self.logger.info(f"取消知网检测任务: {task_id}")
            
            response = await self._make_api_request("DELETE", f"/task/{task_id}")
            
            return response.get("success", False)
            
        except Exception as e:
            self.logger.error(f"取消知网检测任务失败: {e}")
            return False
    
    def _platform_specific_validation(self, text: str) -> bool:
        """知网平台特定验证"""
        # 知网要求最少100字
        if len(text.strip()) < 100:
            return False
        
        # 知网支持中文和英文
        # 这里可以添加更多特定验证逻辑
        return True
    
    def _get_platform_features(self) -> list[str]:
        """获取知网平台特性"""
        return [
            "学术论文检测",
            "期刊文章检测", 
            "学位论文检测",
            "会议论文检测",
            "图书检测",
            "互联网资源检测",
            "支持中英文检测",
            "提供详细相似来源"
        ]
    
    async def get_detection_history(self, limit: int = 10) -> list[Dict[str, Any]]:
        """获取检测历史（知网特有功能）"""
        try:
            self.logger.info("获取知网检测历史")
            
            response = await self._make_api_request(
                "GET", 
                f"/history?limit={limit}"
            )
            
            return response.get("history", [])
            
        except Exception as e:
            self.logger.error(f"获取检测历史失败: {e}")
            return []
    
    async def get_detailed_report(self, task_id: str) -> Dict[str, Any]:
        """获取详细检测报告（知网特有功能）"""
        try:
            self.logger.info(f"获取详细报告: {task_id}")
            
            response = await self._make_api_request(
                "GET", 
                f"/report/detail/{task_id}"
            )
            
            return {
                "task_id": task_id,
                "similarity_sources": response.get("sources", []),
                "similar_paragraphs": response.get("paragraphs", []),
                "statistics": response.get("statistics", {}),
                "recommendations": response.get("recommendations", [])
            }
            
        except Exception as e:
            self.logger.error(f"获取详细报告失败: {e}")
            raise PlatformAPIException(
                self.platform_name.value, 
                f"获取详细报告失败: {str(e)}"
            ) 